package cc.autoapi.pucong.liteflow.design.core.configuration;

import cc.autoapi.pucong.liteflow.design.controller.DesignController;
import cc.autoapi.pucong.liteflow.design.core.exception.DesignException;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 相关接口的拦截器
 *
 * @author pucong
 */
public class DesignWebRequestInterceptor implements HandlerInterceptor {
    private final DesignCorsFilter designCorsFilter;

    private final AuthorizationInterceptor authorizationInterceptor;

    public DesignWebRequestInterceptor(DesignCorsFilter designCorsFilter, AuthorizationInterceptor authorizationInterceptor) {
        this.designCorsFilter = designCorsFilter;
        this.authorizationInterceptor = authorizationInterceptor;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws DesignException {
        HandlerMethod handlerMethod;
        if (handler instanceof HandlerMethod) {
            handlerMethod = (HandlerMethod) handler;
            handler = handlerMethod.getBean();
            if (handler instanceof DesignController) {
                if (!authorizationInterceptor.isenable()) {
                    return false;
                }
                if (designCorsFilter != null) {
                    designCorsFilter.process(request, response);
                }
                boolean success = authorizationInterceptor.checkLogin(request, response, handlerMethod);
                return success;
            }
        }
        return true;
    }

}
